import Api from '../request/api.js';
import { log, sleep } from '../utils/utils.js';
import Yuekeyun from '../lib/Yuekeyun.js';
import Leying from '../lib/Leying.js';
import Xingyun from '../lib/Xingyun.js';
import puppeteer from 'puppeteer-extra';
import StealthPlugin from 'puppeteer-extra-plugin-stealth';
import { TicketChannel } from '../constant/index.js';
import HappinessApp from '../lib/HappinessApp.js';
import Phoenix from '../lib/Phoenix.js';
puppeteer.use(StealthPlugin());
const pgs = new Yuekeyun();
const hp = new HappinessApp();
const leying = new Leying();
const xingyun = new Xingyun();
const phoenix = new Phoenix();
const API = new Api();

// 定时器
export default async function TaskClient() {
  console.log('++++++ 任务进程已启动 ++++++');
  // 初始化puppeteer
  await sleep(3000);
  await pgs.init();
  await phoenix.init();
  while (true) {
    // 获取任务列表
    const taskList = await API.taskList()
      .then((taskRes) => taskRes.data)
      .catch((error) => {
        log('任务请求异常 ' + error.stack, 'error');
        return null;
      });
    if (!taskList || taskList.length === 0) {
      await sleep(3000);
      continue;
    }
    console.log(process.pid + '本次执行任务: ' + taskList.length);

    for (const task of taskList) {
      let service;
      if (task.channel === TicketChannel.PHOENIX) {
        // 凤凰
        service = pgs;
      } else if (task.channel === TicketChannel.HAPPINESS) {
        // 幸福
        service = hp;
      } else if (task.channel === TicketChannel.LEYING) {
        // 乐影
        service = leying;
      }  else if (task.channel === TicketChannel.XINGYUN) {
        // 星云
        service = xingyun;
      } else if (task.channel === TicketChannel.PHOENIX_MP) {
        // 凤凰小程序
        service = phoenix;
      } else {
        continue;
      }
      try {
        if (task.taskType === 'updateShow') {
          // 更新首页
          await service.updateShow(task.taskData);
        } else if (task.taskType === 'updateCinemas') {
          // 更新院线
          await service.updateCinemas(task.taskData);
        }
      } catch (error) {
        log(
          `任务执行异常 taskItemData:${JSON.stringify(task)} \n` + error.stack,
          'error'
        );
        await sleep(2000);
      }
    }
  }
}
